package com.datagrid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DatagridDataRepo {
	private static Map<String, Map<String, String>> index;
	private static int count = 1;
	
	static {
		index = new HashMap<String, Map<String, String>>();
		for (int i = 1; i < 101; i++) {
			Map<String, String> item = new HashMap<String, String>();
			String id = "id-" + count;
			count++;
			item.put("id", id);	// 用于更新、删除，datagrid可以通过row.id可以获取到
			item.put("firstname", "fn-" + i);
			item.put("lastname", "ln-" + i);
			item.put("phone", i + "www");
			item.put("email", i + "@qq.com");
			index.put(id, item);
		}
	}
	
	public static List<Map<String, String>> get(int page, int rows) {
		List<Map<String, String>> repo = new ArrayList<Map<String, String>>(index.values());
		
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		// rows, (page-1)*rows
		int from = (page - 1) * rows;
		int length = repo.size();
		for (int i = from; i < length && rows > 0; i++,rows--) {
			list.add(repo.get(i));
		}
		return list;
	}
	
	public static void addItem(Map<String, String> item) {
		String id = "id-" + count;
		item.put("id", id);
		count++;
		index.put(id, item);
	}
	
	public static int size() {
		return index.size();
	}

	public static void updateItem(Map<String, String> item) {
		index.put(item.get("id"), item);
	}
	
	public static void removeItem(String id) {
		index.remove(id);
	}
}
